﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MREO.data;
using System.Diagnostics;

namespace MREO.gui
{
    public partial class fMain : Form
    {
        DataTable mnuDt;

        public fMain(DataTable pMnuDt)
        {
            mnuDt = pMnuDt;

            InitializeComponent();

            tabControl_top.SelectedIndexChanged += new EventHandler(tabControl_top_SelectedIndexChanged);
        }

        /// <summary>
        /// Обновляем меню
        /// </summary>
        /// <param name="pnewMnu">DataTable содержащее новое меню</param>
        public void updateMNU(DataTable pnewMnu)
        {
            mnuDt = pnewMnu;
            fMain_Shown(new object(), new EventArgs());
        }

        void tabControl_top_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl_top.SelectedTab == null) return;

            foreach (Form form in MdiChildren)
            {
                Debug.Print("tabControl_top.SelectedIndex:" + tabControl_top.SelectedIndex.ToString());

                switch (form.GetType().Name)
                {
                    case "fPresent":
                        if (((fPresent)form).tabKey.Equals(tabControl_top.SelectedTab.Tag.ToString()))
                            form.Focus();
                        break;

                    case "fTemplates":
                        if (((fTemplates)form).tabKey.Equals(tabControl_top.SelectedTab.Tag.ToString()))
                            form.Focus();
                        break;

                    case "fGVal":
                        if (((fGVal)form).tabKey.Equals(tabControl_top.SelectedTab.Tag.ToString()))
                            form.Focus();
                        break;

                    case "fGroupDocObjects":
                        if (((fGroupDocObjects)form).tabKey.Equals(tabControl_top.SelectedTab.Tag.ToString()))
                            form.Focus();
                        break;
                }
            }
        }

        private void fMain_Shown(object sender, EventArgs e)
        {
            tSDDButton_statements.DropDownItems.Clear();
            tSDDButton_contract.DropDownItems.Clear();

            foreach (DataRow dr in mnuDt.AsEnumerable())
            {
                ToolStripMenuItem item = new ToolStripMenuItem();

                switch (long.Parse(dr["doc_type"].ToString()))
                {
                    case 0:             // Заявления
                        item.Text = dr["doc_name"].ToString();
                        item.Tag = new object[] { dr["id"].ToString(), dr["template"] };
                        item.Click += new EventHandler(item_Click);
                        tSDDButton_statements.DropDownItems.Add(item);
                        break;

                    case 1:             // Договора
                        item.Text = dr["doc_name"].ToString();
                        item.Tag = new object[] { dr["id"].ToString(), dr["template"] };
                        item.Click += new EventHandler(item_Click);
                        tSDDButton_contract.DropDownItems.Add(item);
                        break;

                    case 2:             // Карточка
                        tSButton_card.Tag = new object[] { dr["id"].ToString(), dr["template"] };
                        tSButton_card.Click += new EventHandler(tSButton_card_Click);
                        break;
                }
            }

            tSSLabel_fio.Text = "Вы вошли в систему как: " + GValues._userFIO;
        }

        void tSButton_card_Click(object sender, EventArgs e)
        {
            int tabIndex;
            string tabKey = DateTime.Now.ToString();

            ToolStripButton item = sender as ToolStripButton;
            object[] itemTag = (object[])item.Tag;
            Template templ = new Template();

            #region Проверка отображается ли уже пункт
            //for (int i = 0; i < tabControl_top.TabPages.Count; i++)
            //{
            //    if (tabControl_top.TabPages[i].Text.Equals(item.Text))
            //    {
            //        tabControl_top.TabPages[i].Show();
            //        return;
            //    }
            //}
            #endregion

            templ._name = item.Text;
            templ._id = long.Parse(itemTag[0].ToString());
            templ._templ = itemTag[1] == System.DBNull.Value ? null : (byte[])itemTag[1];


            tabIndex = tabControl_top.TabPages.Count;
            TabPage tp = new TabPage();
            tp.Text = templ._name;
            tp.Tag = tabKey;
            tabControl_top.TabPages.Add(tp);
            tabControl_top.SelectedIndex = tabIndex;

            fPresent fpres = new fPresent(templ);
            fpres.Text = templ._name;
            fpres.MdiParent = this;
            fpres.tabIndex = tabIndex;
            fpres.tabKey = tabKey;
            fpres.FormClosed += new FormClosedEventHandler(fpres_FormClosed);
            fpres.Show();
        }

        private void item_Click(object sender, EventArgs e)
        {
            int tabIndex;
            string tabKey = DateTime.Now.ToString();

            ToolStripMenuItem item = sender as ToolStripMenuItem;
            object[] itemTag = (object[])item.Tag;
            Template templ = new Template();

            #region Проверка отображается ли уже пункт
            //for (int i = 0; i < tabControl_top.TabPages.Count; i++)
            //{
            //    if (tabControl_top.TabPages[i].Text.Equals(item.Text))
            //    {
            //        tabControl_top.TabPages[i].Show();
            //        return;
            //    }
            //}
            #endregion

            templ._name = item.Text;
            templ._id = long.Parse(itemTag[0].ToString());
            templ._templ = itemTag[1] == System.DBNull.Value ? null : (byte[])itemTag[1];
                

            tabIndex = tabControl_top.TabPages.Count;
            TabPage tp = new TabPage();
            tp.Text = templ._name;
            tp.Tag = tabKey;
            tabControl_top.TabPages.Add(tp);
            tabControl_top.SelectedIndex = tabIndex;

            fPresent fpres = new fPresent(templ);
            fpres.Text = templ._name;
            fpres.MdiParent = this;
            fpres.tabIndex = tabIndex;
            fpres.tabKey = tabKey;
            fpres.FormClosed += new FormClosedEventHandler(fpres_FormClosed);
            fpres.Show();
        }

        void fpres_FormClosed(object sender, FormClosedEventArgs e)
        {
            foreach (TabPage tp in tabControl_top.TabPages)
            {
                if (tp.Tag.ToString().Equals(((fPresent)sender).tabKey))
                {
                    tabControl_top.TabPages.Remove(tp);
                }
            }
        }

        private void TlMItem_Templates_Click(object sender, EventArgs e)
        {
            int tabIndex;
            string tabKey = DateTime.Now.ToString();

            tabIndex = tabControl_top.TabPages.Count;
            TabPage tp = new TabPage();
            tp.Text = "Шаблоны";
            tp.Tag = tabKey;
            tabControl_top.TabPages.Add(tp);
            tabControl_top.SelectedIndex = tabIndex;

            fTemplates fTempl = new fTemplates(mnuDt);
            fTempl.tabKey = tabKey;
            fTempl.MdiParent = this;
            fTempl.FormClosed += new FormClosedEventHandler(fTempl_FormClosed);
            fTempl.Show();
        }

        void fTempl_FormClosed(object sender, FormClosedEventArgs e)
        {
            foreach (TabPage tp in tabControl_top.TabPages)
            {
                if (tp.Tag.ToString().Equals(((fTemplates)sender).tabKey))
                {
                    tabControl_top.TabPages.Remove(tp);
                }
            }
        }

        private void ToolStripMenuItem_GVal_Click(object sender, EventArgs e)
        {
            int tabIndex;
            string tabKey = DateTime.Now.ToString();

            tabIndex = tabControl_top.TabPages.Count;
            TabPage tp = new TabPage();
            tp.Text = "Глобальные переменные";
            tp.Tag = tabKey;
            tabControl_top.TabPages.Add(tp);
            tabControl_top.SelectedIndex = tabIndex;

            fGVal fgval = new fGVal();
            fgval.tabKey = tabKey;
            fgval.MdiParent = this;
            fgval.FormClosed += new FormClosedEventHandler(fgval_FormClosed);
            fgval.Show();

        }

        void fgval_FormClosed(object sender, FormClosedEventArgs e)
        {
            foreach (TabPage tp in tabControl_top.TabPages)
            {
                if (tp.Tag.ToString().Equals(((fGVal)sender).tabKey))
                {
                    tabControl_top.TabPages.Remove(tp);
                }
            }
        }

        private void TSMItem_ACL_Click(object sender, EventArgs e)
        {
            fLogOn fEnter = new fLogOn();
            fEnter.ShowDialog();

            if (fEnter.oUser != null){
                if (fEnter.oUser._lvl != 1){
                    MessageBox.Show("Для доступа в данный пункт необходимы права администратора.");
                    return;
                }
            }

            fUsers fu = new fUsers();
            fu.ShowDialog();
        }

        private void TSMItem_reports_Click(object sender, EventArgs e)
        {
            fLogOn fEnter = new fLogOn();
            fEnter.ShowDialog();

            if (fEnter.oUser != null)
            {
                if (fEnter.oUser._lvl != 1)
                {
                    MessageBox.Show("Для доступа в данный пункт необходимы права администратора.");
                    return;
                }
            }

            fReports frep = new fReports();
            frep.ShowDialog();
        }


        private void TSMItem_SellBayContract_Click(object sender, EventArgs e)
        {
            int tabIndex = tabControl_top.TabPages.Count;
            string tabKey = DateTime.Now.ToString();

            TabPage tp = new TabPage();
            tp.Text = "Снятие+Постановка на учет+Договор";
            tp.Tag = tabKey;
            tabControl_top.TabPages.Add(tp);
            tabControl_top.SelectedIndex = tabIndex;

            fGroupDocObjects fgroupDoc = new fGroupDocObjects("docBaySell", new docBaySell() );
            fgroupDoc.Text = "Снятие+Постановка на учет+Договор";
            fgroupDoc.tabKey = tabKey;
            fgroupDoc.MdiParent = this;
            fgroupDoc.FormClosed += new FormClosedEventHandler(fgroupDoc_FormClosed);
            fgroupDoc.Show();
        }

        void fgroupDoc_FormClosed(object sender, FormClosedEventArgs e)
        {
            foreach (TabPage tp in tabControl_top.TabPages)
            {
                if (tp.Tag.ToString().Equals(((fGroupDocObjects)sender).tabKey))
                {
                    tabControl_top.TabPages.Remove(tp);
                }
            }
        }
    }
}
